import 'dart:convert';

import 'package:dio/dio.dart';

import 'api_chat_asyn.dart';

class ChatStreamHandler {
    Stream<String> handleChatStream(Map<String, dynamic> body) async* {
      print('--------------handleChatStream-->>>>> $body');
      try {
        // 直接获取 ResponseBody
        final responseBody = await ApiChatAsynClient.instance.chatSendStreamResponse(body);

        // 从 responseBody.stream 中读取数据
        await for (final data in responseBody.stream) {
          try {
            // 尝试 UTF-8 解码
            final content = utf8.decode(data);
            print('--------------尝试 UTF-8 解码-->>>>> $content');
            yield content;
          } catch (decodeError) {
            print('Decode error: $decodeError');
            // 如果解码失败，尝试使用 latin1 编码
            try {
              final content = String.fromCharCodes(data);
              print('--------------尝试 latin1 解码-->>>>> $content');
              yield content;
            } catch (e) {
              yield 'Decode error: $e';
            }
          }
        }
      } on DioException catch (e) {
        print('DioException: ${e.message}');
        if (e.type == DioExceptionType.receiveTimeout) {
          yield "Error: 请求超时，请稍后重试";
        } else {
          yield "Error: ${e.message}";
        }
      } catch (e) {
        print('Exception: $e');
        yield "Exception: $e";
      }
  }
}
